package com.chat.websocket;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.chat.vo.params.OnlinePeopleVo;
import com.chat.websocket.online.OnlineManage;

/**
 * websocket处理器
 * 
 * @author lwh
 *
 */
@Component
public class SystemHandler implements WebSocketHandler {
	private static final Logger logger = Logger.getLogger(SystemHandler.class);
	/**
	 * 获取uri参数
	 * 
	 * @return
	 */
	public Map<String, String> getParameter(WebSocketSession session) {
		Map<String, String> map = new HashMap<String, String>(0);
		String uri = session.getUri().toString();
		String[] strs = uri.split("/");
		if (strs.length > 3) {
			map.put("userName", strs[strs.length - 2]);
			map.put("token", strs[strs.length - 1]);
		}
		return map;
	}

	/**
	 * 用户关闭连接后触发
	 */
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		logger.info("用户关闭连接触发事件");
		OnlineManage.removeOnlineUser(session,closeStatus);
	}

	/**
	 * 用户连接上后触发
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		logger.info(" 用户连接上触发事件");
		// 创建用户连接信息
		OnlinePeopleVo opv = new OnlinePeopleVo();
		Map<String, String> Parameters = this.getParameter(session);
		opv.setUserName( Parameters.get("userName") );
		opv.setToken( Parameters.get("token") );
		opv.setCreatetime( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) );
		opv.setSession(session);
		// 加入在线
		OnlineManage.addToOnlineUserList(opv);
	}

	/**
	 * 接收到信息时触发
	 */
	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		logger.info(" 用户接收到信息触发事件");
		session.sendMessage(new TextMessage("警告：请不要使用WebSocket来发送信息，请使用HTTP协议发送信息，使用WebSocket监听服务器推送的信息"));
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
	}

	@Override
	public boolean supportsPartialMessages() {
		return false;
	}

}
